// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import VueResource from 'vue-resource'
Vue.use(VueResource)
Vue.http.options.root = 'http://127.0.0.1:3001/'
Vue.config.productionTip = false

import './components/common/style.css'
import './lib/mui/css/mui.css'
import Vuex from 'vuex'
Vue.use(Vuex);
var car = JSON.parse(localStorage.getItem('car')||'[]');
const store = new Vuex.Store({
  state:{
    car: car
  },
  getters:{
    getAllCount(state){
      //获取所有数量
      let c =0;
      state.car.forEach( item =>{
         c += item.count;
      })
      return c;
    },
    getGoodsCount(state){
      let o ={};
      state.car.forEach(item =>{
        o[item.id] = item.count;
      });
      return o;
    },
    getGoodsCountAndAmount(state){
      let o ={
        count: 0,
        amount: 0
      };
      state.car.forEach( item =>{
          o.count += item.count;
          o.amount += item.count * item.price;
      })
      return o;
    }
  },
  mutations:{
    //把信息保存到购物车
    updateToCar(state, goodsinfo){
      var flag = false;
      state.car.some( (item,i) =>{
        if(item.count <= 0){
          //删除该条商品
          state.car.splice(i ,1);
        }
        if(item.id === goodsinfo.id){
          flag = true;
          if(goodsinfo.count <= 0){
            //删除该条商品
            state.car.splice(i ,1);
            return true;
          }
          item.count = parseInt(goodsinfo.count);
          return true;
        }
      })
      if(!flag){
        state.car.push(goodsinfo);
      }
      localStorage.setItem('car',JSON.stringify(state.car));
    },
    //清空购物车
    delCar(state){
      state.car = [];
      localStorage.setItem('car',JSON.stringify(state.car));
    }
  }
});
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>',
  store
})
